import { useState, useEffect, useRef } from 'react';
import style from './style.module.scss'
import { Button } from 'antd';
import type { SparkRequest, SparkResponse, StoreData, StoredReport } from '@/Interface/AiCmpInterface';
import { generateAuthUrl, generateDataHash } from './generate';

// 添加本地存储键名
const STORAGE_KEY = "store_analysis_report"

// 凭证信息
const APP_ID = import.meta.env.VITE_SPARK_APPID;


const StoreComparison: React.FC<{ stores: StoreData[] }> = ({ stores }) => {
  const [report, setReport] = useState<string>('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string>('');
  const ws = useRef<WebSocket | null>(null);


  // 初始化时加载存储的报告
  useEffect(() => {
    try {
      const saved = sessionStorage.getItem(STORAGE_KEY);
      if (!saved) {
        setReport('');
        return;
      }

      const parsed: StoredReport = JSON.parse(saved);

      // 验证数据是否匹配当前门店
      const currentHash = generateDataHash(stores);
      if (parsed.hash === currentHash) {
        setReport(parsed.content);
      } else {
        sessionStorage.removeItem(STORAGE_KEY)
        setReport('');
      }
    } catch (error) {
      console.error('加载缓存报告失败:', error);
    }
  }, [stores]); // stores变化时重新检查


  // 保存报告到本地存储
  const persistReport = (content: string) => {
    const reportData: StoredReport = {
      hash: generateDataHash(stores),
      timestamp: Date.now(),
      content,
    };

    try {
      sessionStorage.setItem(STORAGE_KEY, JSON.stringify(reportData));
    } catch (error) {
      console.warn('本地存储空间不足，未能保存报告');
    }
  };


  // 构造请求内容
  const buildPrompt = (stores: StoreData[]): string => {
    return `你是一名连锁餐饮数据分析专家，请对比以下两家门店，直接总结出分析结果以及建议：
    门店信息：${JSON.stringify(stores[0])}
    门店信息：${JSON.stringify(stores[1])}
    生成两段纯文本回答，尽量使用文字，少用括号列举数据，
    第一段为对比结果，第二段为建议，且都有【】包裹的标题独占一行，不要分点作答。
    `;
  };

  // 发起请求
  const generateReport = async () => {

    setLoading(true);
    setError('');
    setReport('');

    try {
      const url = generateAuthUrl();
      ws.current = new WebSocket(url);

      ws.current.onopen = () => {
        const request: SparkRequest = {
          header: {
            app_id: APP_ID,
            uid: "user"
          },
          parameter: {
            chat: {
              domain: "generalv3.5",
              max_tokens: 1024,
              temperature: 0.1,
              tools: [
                {
                  type: "web_search",
                  web_search: {
                    enable: true,
                    search_mode: "normal"
                  }
                }
              ]
            }
          },
          payload: {
            message: {
              text: [{
                role: "user",
                content: buildPrompt(stores)
              }]
            }
          }
        };
        ws.current?.send(JSON.stringify(request));
      };

      ws.current.onmessage = (event) => {
        const response: SparkResponse = JSON.parse(event.data);

        if (response.header.code !== 0) {
          setError(`错误码 ${response.header.code}: ${response.header.message}`);
          return;
        }
        let newContent: string;
        // 拼接响应内容
        if (response.payload.choices?.text?.[0]?.content) {
          setReport(prev => {
            newContent = prev + response.payload.choices.text[0].content;

            // 处理最终结果
            if (response.header.status === 2) {
              persistReport(newContent);
              setLoading(false);
              ws.current?.close();
            }
            return newContent;
          });
        }
      };

      ws.current.onerror = (_error) => {
        setError('WebSocket连接错误');
        setLoading(false);
      };

    } catch (error) {
      setError('请求初始化失败');
      setLoading(false);
    }
  };

  // 组件卸载时关闭连接
  useEffect(() => {
    return () => {
      if (ws.current) {
        ws.current.close();
      }
    };
  }, []);

  return (
    <div className={style.comparison}>
      <div className={style.top}>
        <h4>AI智能分析</h4>
        <div>
          <Button
            type='primary'
            onClick={generateReport}
            disabled={loading}
          >
            {loading ? '生成中...' : '生成对比报告'}
          </Button>
        </div>
      </div>
      {error && <div>{error}</div>}

      {report && (
        <div className={style.content}>
          <pre>{report}</pre>
        </div>
      )}
    </div>
  );
};

export default StoreComparison;